import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/common/widget/conform_dialog.dart';
import 'package:casdon/core/auth/auth_storage.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/core/utils/page_visibility_mixin.dart';
import 'package:casdon/modules/me/application/notification/social_account_notifier.dart';
import 'package:casdon/modules/me/domain/states/social_binded_list_state.dart';
import 'package:casdon/modules/me/ui/widgets/form_field_item.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

@RoutePage()
class AccountSecurityScreen extends ConsumerStatefulWidget {
  const AccountSecurityScreen({super.key});
  @override
  ConsumerState<AccountSecurityScreen> createState() =>
      _AccountSecurityScreenState();
}

class _AccountSecurityScreenState extends ConsumerState<AccountSecurityScreen>
    with PageVisibilityMixin, WidgetsBindingObserver {
  bool _isInitialized = false; // ✅ 防止重复初始化

  @override
  void initState() {
    super.initState();

    _loadInitialData();
  }

  void _loadInitialData() {
    if (_isInitialized) return;

    final socialNotifier = ref.read(socialAccountNotifierProvider.notifier);
    socialNotifier.getSocialList();
    _isInitialized = true;
  }

  @override
  Widget build(BuildContext context) {
    final socialState = ref.watch(socialAccountNotifierProvider);

    _setupStateListener();

    return buildPageVisibilityDetector(
      context,
      Scaffold(
        appBar: const CommonAppBar(title: "账号与安全"),
        body: Container(
          color: context.colorScheme.surface,
          child: Column(
            children: [
              _buildGap(context),
              _buildUserAccount(ref),
              _buildModifyPassword(context, ref),
              _buildGap(context),
              _buildWechatAccount(socialState, context, ref),
              _buildAppleAccount(socialState, context, ref),
              _buildGap(context),
              _buildDeleteAccount(context, ref),
            ],
          ),
        ),
      ),
    );
  }

  // ✅ 将每个FormFieldItem拆分为独立方法
  Widget _buildUserAccount(WidgetRef ref) {
    return FutureBuilder<String>(
      future: ref
          .read(authStorageProvider.notifier)
          .getUserAccount()
          .then((s) => s ?? ''),
      builder: (context, snapshot) {
        return FormFieldItem(
          label: '账号',
          value: snapshot.data ?? '',
          isRequired: false,
          isEditable: false,
          showArrow: false,
          backgroundColor: Colors.white,
        );
      },
    );
  }

  Widget _buildModifyPassword(BuildContext context, WidgetRef ref) {
    return FormFieldItem(
      label: '修改登录密码',
      isRequired: false,
      showArrow: true,
      isEditable: false,
      showBottomDivider: false,
      backgroundColor: Colors.white,
      onTap: () => _goModifyPwdScreen(context, ref),
    );
  }

  Widget _buildWechatAccount(
    SocialBindedListState state,
    BuildContext context,
    WidgetRef ref,
  ) {
    return FormFieldItem(
      label: '微信账号',
      hintText: state.wxAccount == null ? '未绑定' : null,
      value: state.wxAccount,
      isRequired: false,
      isEditable: false,
      showArrow: true,
      backgroundColor: Colors.white,
      onTap: () => _handleWechatAccount(state, context, ref),
    );
  }

  Widget _buildAppleAccount(
    SocialBindedListState state,
    BuildContext context,
    WidgetRef ref,
  ) {
    return FormFieldItem(
      label: 'Apple账号',
      hintText: state.appleAccount == null ? '未绑定' : null,
      value: state.appleAccount,
      isRequired: false,
      isEditable: false,
      showArrow: true,
      showBottomDivider: false,
      backgroundColor: Colors.white,
      onTap: () async => _handleAppleAccount(state, context, ref),
    );
  }

  Widget _buildDeleteAccount(BuildContext context, WidgetRef ref) {
    return FormFieldItem(
      label: '注销账号',
      isRequired: false,
      isEditable: false,
      showArrow: true,
      showBottomDivider: false,
      backgroundColor: Colors.white,
      onTap: () => _handleDelAccountScreen(context, ref),
    );
  }

  Widget _buildGap(BuildContext context) {
    return ColoredBox(
      color: context.colorScheme.surface,
      child: const SizedBox(height: 8, width: double.infinity),
    );
  }

  // ✅ 空方法改为实际导航逻辑
  void _goModifyPwdScreen(BuildContext context, WidgetRef ref) async {
    final account = await ref
        .read(authStorageProvider.notifier)
        .getUserAccount();
    if (account == null) return;
    if (context.mounted == false) return;
    VerifyIdentityRoute(account: account, title: "验证身份").push(context);
  }

  void _handleDelAccountScreen(BuildContext context, WidgetRef ref) {
    DelAccountRoute().push(context);
  }

  void _handleAppleAccount(
    SocialBindedListState state,
    BuildContext context,
    WidgetRef ref,
  ) async {
    if (state.appleAuthId == null) {
      // 未绑定，则绑定操作
      ref
          .read(socialAccountNotifierProvider.notifier)
          .bindSocial(source: SocialBindedListState.KAppleSource);
    } else {
      // 已绑定，则弹出提示是否取消绑定
      if (context.mounted == false) {
        return;
      }
      final ret = await showCustomConfirmDialog(
        context: context,
        content: "确定取消绑定 ？",
      );
      if ((ret ?? false) && context.mounted) {
        ref
            .read(socialAccountNotifierProvider.notifier)
            .delBindSocial(source: SocialBindedListState.KAppleSource);
      }
    }
  }

  void _handleWechatAccount(
    SocialBindedListState state,
    BuildContext context,
    WidgetRef ref,
  ) async {
    if (state.wxId == null) {
      // 未绑定，则绑定操作
      if (context.mounted) {
        ref
            .read(socialAccountNotifierProvider.notifier)
            .bindSocial(source: SocialBindedListState.KWXSource);
      }
    } else {
      // 已绑定，则弹出提示是否取消绑定

      if (context.mounted == false) {
        return;
      }
      final ret = await showCustomConfirmDialog(
        context: context,
        content: "解绑后将无法继续使用它登录该凯度生活家账号？",
        confirmText: "确定解绑",
      );
      if ((ret ?? false) && context.mounted) {
        ref
            .read(socialAccountNotifierProvider.notifier)
            .delBindSocial(source: SocialBindedListState.KWXSource);
      }
    }
  }

  @override
  void onPageVisible() {
    ref.read(socialAccountNotifierProvider.notifier).resetBindinInFlight();
  }

  void _setupStateListener() {
    ref.listen<SocialBindedListState>(socialAccountNotifierProvider, (
      previous,
      next,
    ) {
      if (next.errorMsg == null || next.errorMsg!.isEmpty) {
        return;
      }
      ToastUtil.show("${next.errorMsg}");
    });
  }
}
